﻿using CodeNotes.BLL;
using CodeNotes.Common;
using CodeNotes.Model;
using MvcCodeNotes.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace MvcCodeNotes.Controllers.api
{
    public class MusicController : ApiController
    {
        // GET api/music 
        //获取music列表
        //返回码
        //0:成功
        //1:用户名或密码错误
        //101:音乐接口，已经是最新版本
        //102:音乐接口，其他错误。。。
        //500:接口报错
        //404:not found

        public ApiResult<ApiMusicData> Get()
        {
            ApiResult<ApiMusicData> a = new ApiResult<ApiMusicData>();
            if (Request.Headers.Contains("username") && Request.Headers.Contains("pwd"))
            {
                string username = Request.Headers.GetValues("username").First().ToString();
                string pwd = Request.Headers.GetValues("pwd").First().ToString();
                bool isInVersion = false;
                CW_ApiSetting musicSetting = new CW_ApiSettingLogic().GetModelList("ApiType='music'")[0];
                string v = musicSetting.Version;
                string jsonStr = musicSetting.Json;
                if (Request.Headers.Contains("version"))
                {
                    //校验是否是最新版本
                    string version = Request.Headers.GetValues("version").First().ToString();
                    if (musicSetting.Version == version)
                        isInVersion = true;
                }
                if (!isInVersion)
                {
                    string sqlStr = "1=1";
                    if (jsonStr != "")
                    {
                        sqlStr = "id in (" + jsonStr.Trim(',') + ")";
                    }
                    List<CW_Music> temp = new CW_MusicLogic().GetModelList(sqlStr);
                    List<CW_Music> musics = new List<CW_Music>();
                    if (jsonStr == "")
                    {
                        musics = temp;
                    }
                    else
                    {
                        string[] ids = jsonStr.Split(',');
                        for (int i = 0; i < ids.Length; i++)
                        {
                            string id = ids[i];
                            CW_Music model = temp.Find(m => m.Id.ToString() == id);
                            if (model != null && model.Id > 0)
                                musics.Add(model);
                        }
                    }
                    a.errcode = "0";
                    a.errmsg = "ok";
                    a.data = new ApiMusicData()
                    {
                        version = v,
                        list = musics
                    };
                }
                else
                {
                    a.errcode = "1";
                    a.errmsg = "已是最新版本！";
                }
            }
            else
            {
                a.errcode = "2";
                a.errmsg = "用户名或密码不对";
            }
            return a;
        }

        // GET api/music/5
        public ApiResult<List<CW_Music>> Get(string keyword)
        {
            Log.LogNote("api/music/keyword", "搜索歌曲：" + keyword, "error");

            ApiResult<List<CW_Music>> a = new ApiResult<List<CW_Music>>();
            string url = "http://route.showapi.com/213-1?showapi_sign=3f0c698c4357477ba780198b22f4eeaf&showapi_appid=35037&keyword=" + keyword;
            try
            {
                CW_MusicLogic logic = new CW_MusicLogic();
                string EncodingStr = "UTF-8";
                string html = BookFetch.GetHtml(url, EncodingStr);
                JavaScriptSerializer Serializer = new JavaScriptSerializer();
                ShowapiModel result = Serializer.Deserialize<ShowapiModel>(html);


                if (result.showapi_res_body != null && result.showapi_res_body.pagebean != null && result.showapi_res_body.pagebean.contentlist != null)
                {
                    List<SongModel> songlist = result.showapi_res_body.pagebean.contentlist;
                    List<CW_Music> resultlist = new List<CW_Music>();
                    foreach (SongModel model in songlist)
                    {
                        CW_Music newModel = new CW_Music();
                        newModel.url = model.m4a;
                        newModel.seconds = model.seconds;
                        newModel.singername = model.singername;
                        newModel.songid = model.songid;
                        newModel.songname = model.songname;
                        newModel.albumpic = model.albumpic_small;
                        resultlist.Add(newModel);
                    }
                    a.errcode = "0";
                    a.errmsg = "ok";
                    a.data = resultlist;
                }
                else
                {
                    a.errcode = "404";
                    a.errmsg = "接口没有找到";
                    Log.LogNote("api/music/keyword", "接口没有找到：" + keyword, "error");
                }
            }
            catch (Exception ex)
            {
                a.errcode = "500";
                a.errmsg = ex.Message.ToString();

                Log.LogNote("api/music/keyword", ex.Message.ToString(), "error");
            }
            return a;
        }

        private void SearchMusic(string keyword)
        {


        }

        // POST api/music        
        public void Post([FromBody]string value)
        {

        }

        // PUT api/music/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/music/5
        public void Delete(int id)
        {
        }
    }
}
